var express = require('express');
var router = express.Router();
var User = require('../model/user');
var Man = require('../model/manage');
var Shop = require('../model/shops');
const multer = require('multer');
var validator = require('validator');
// 注册
router.post('/zhuce',function(req,res,next){
  console.log(req.body);
  let name = req.body.name;
  let password = req.body.password;
  let phone = req.body.phone;
  var err;
  if(!validator.matches(name,/^[a-zA-Z][a-zA-Z0-9_]{4,11}$/,'g')){
    err = '用户名格式不正确,以字母开头'
  }
  if(!validator.matches(password,/^[a-zA-Z0-9]\w{5,17}$/,'g')){
    err = "密码格式不正确"
  }
  if(err){
    return res.json({error:1,message:''})(err);
  }
    User.findOne().or([{name:name}, {phone:phone}]).then( (user) => {
        if(user){
            return res.json({error:1,message:'用户或手机号已存在'})             
        }
        let newUser = new User(req.body);
        newUser.save().then( (data) =>{
            res.json({error:0,message:'注册成功'})
        }).catch((err)=>{
            res.json({error:1,message:'注册失败'});
        })
    }).catch((err) => {
        res.jion({error:1,message:''})(err);
    })

})
// 管理登录
router.post('/deng',function(req,res,next){
    let name = req.body.name;
    let password = req.body.password;
    let getName;
    let getPon;
    validator.isNumeric(name) ? getPon = name :  getName = name;
    if( getName ){
        if( !validator.matches(name,/^[a-zA-Z][a-zA-Z0-9_]{4,11}$/, 'g') ){
            return res.json({error:1,message:'用户名不合法，以字母开头，数字、字母、_'})
        }
    }
    if(getPon){
        if (!validator.matches(name, /^(13|14|15|17|18)\\d{8}}$/, 'g')) {
            return res.json({error:1,message:'手机格式不正确'})
        }
    }
    if (!validator.matches(password, /^[a-zA-Z0-9]\w{5,17}$/, 'g')) {
        return res.json({error:1,message:'密码格式不正确'})
    }
     let getMan;
     if(getName){
         getMan = Man.getManByName;
     }
    if(getPon){
        getMan = Man.getManByPhone;
     }
  getMan(name, function(err, user){
        if(err){
            return res.end(err);
        }
        if(!user){
            return res.json({error:1,message:'用户/手机号不存在，请注册...'});
        }
        if( password !== user.password ){
            return res.json({error:1,message:'密码不相等，请重新输入'});
        }
        req.session.poat = user
        res.json({error:0,post:req.session.poat})
    })
})
// 用户登录
router.post('/login',function(req,res,next){
    let name = req.body.name;
    let password = req.body.password;
    let getName;
    let getPon;
    validator.isNumeric(name) ? getPon = name :  getName = name;
    if( getName ){
        if( !validator.matches(name,/^[a-zA-Z][a-zA-Z0-9_]{4,11}$/, 'g') ){
            return res.json({error:1,message:'用户名不合法，以字母开头，数字、字母、_'})
        }
    }
    if(getPon){
        if (!validator.matches(name, /^(13|14|15|17|18)\\d{8}}$/, 'g')) {
            return res.json({error:1,message:'手机格式不正确'})
        }
    }
    if (!validator.matches(password, /^[a-zA-Z0-9]\w{5,17}$/, 'g')) {
        return res.json({error:1,message:'密码格式不正确'})
    }
     let getUser;
     if(getName){
         getUser = User.getUserByName;
     }
    if(getPon){
        getUser = User.getUserByPhone;
     }
    // console.log(4)
    // console.log(getUser)
    // console.log(name)
  getUser(name, function(err, user){
    //   console.log(5)
    //   console.log(user)
        if(err){
            return res.end(err);
        }
        if(!user){
            return res.json({error:1,message:'用户/手机号不存在，请注册...'});
        }
        if( password !== user.password ){
            return res.json({error:1,message:'密码不相等，请重新输入'});
        }
        req.session.user = user
        res.json({error:0,mrssage:req.session.user})
    })
})

// 登录者信息
router.get('/login',function(req,res,next){
    let name = req.session.user;
    let post = req.session.poat;
    // console.log(name);
    res.json({error:0,message:{name:name,post:post}});
})
// 获取购物车数据
router.get('/shopcart',function(req,res,next){
    // console.log(req.session.user.name)
    var name = req.session.user.name
    User.findOne({name:name}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:'获取数据失败'});
        }
        res.json({error:0,message:data});
    })
    
})

// 退出
router.get('/tuichu',function(req,res,next){
    req.session.user = null;
    req.session.poat = null;
    res.json({error:0,message:req.session})
})


// 设置文件磁盘存储
var storage = multer.diskStorage({
    destination:'./public/images/photos',
    filename: function (req, file, cb) { 
        var suffix = file.mimetype.split("/")[1];
        cb(null, file.fieldname + '-' + Date.now() + '.'+ suffix);
    }
});
//通过multer处理当前文件的存储
var upload = multer({ storage: storage })
// 添加商品
router.post('/update',upload.array('photo'), function(req,res){
    console.log(req.body,'======');
    console.log(req.files);  
    var arr = []
    for(var i = 0 ; i < req.files.length; i++){
        arr.push(req.files[i].filename)
    }
    req.body.productImage = arr
    let newShop = new Shop(req.body);
    console.log(newShop);  
    newShop.save(function(err){
        console.log('--2--');
        if(err){
            console.log('--3--');
            return res.json({error:1,message:'添加失败'});
        }
        console.log('--4--');
        res.json({error:0,message:'添加成功',url:`${newShop._id}`,user:req.session.user});
    })
});


// 全部商品首页显示
router.get('/shop',function(req,res){
    Shop.find().exec(function(err,data){
        if(err){
            return res.json({error:1,message:'获取失败'})
        }
        res.json({error:0,message:data})

    })
})
// 详情页面
router.get('/xiang/:id',function(req,res){
    // console.log(req.params.id);
    var id = req.params.id
     Shop.findOne({_id:id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:'获取失败'})
        }
        res.json({error:0,message:data})

    })
})

// 加入购物车
router.post('/addcart',function(req,res){
    // console.log(req.body.shop_id)
    var productId = req.body.shop_id;
    // console.log(req.session.user._id)
    var user_id = req.session.user._id;
    // console.log('1')
        Shop.findOne({_id:productId}).exec(function(err,data){
        // console.log('2')
        if(err){
            return res.json({error:1,message:'商品获取失败'})
        }
        // console.log('3')
        User.findOne({_id:user_id}).exec(function(err,user){
            // console.log('4')
            if(err){
                return res.json({error:1,message:'用户获取失败'})
            }
            // console.log('5')
            var isCun = false;
            // console.log(user.cart)
            // console.log(user.cart.length)
            if(user.cart.length > 0){
                // console.log('6')
                user.cart.forEach(function(item) {
                    if(item.productId == productId){
                        item.productNum += 1;
                        user.save();
                        isCun = true;
                    }
                });

            }
            if(!isCun){
                // console.log(data)
                user.cart.push({
                    "productId":data._id,
                    "productName":data.name,
                    "salePrice":data.price,
                    "productImage":data.productImage,
                    "checked":data.checked,
                    "productNum":1,
                    "describe":data.describe,
                    "yuanPrice":data.yuanPrice,
                    "xuan":data.xuan,
                })
                // console.log('9')
                user.save();
            }
            res.json({error:0,message:'添加成功'})
        })
    })

})


// 删除购物车中商品
router.get('/remove',function(req,res){
    // console.log(req.session.user._id)
    // console.log(req.query.id)
    var user_id = req.session.user._id;
    var sid = req.query.id;
    // console.log(1)
     User.findOne({ '_id': user_id}).exec(function(err,data){
        // console.log(2)
        if(err){
            return res.end(err);
        }
        // console.log(3)
        data.cart.forEach(function(item,index){
            // console.log(4)
            if(item.productId == sid){
                // console.log(5)
                // console.log(data.cart)
                data.cart.splice(index,1);
                data.save();
            }
            // console.log(6)
        })
        res.json({error:0,messahe:'删除成功'})
    })
})
// 管理删除商品
router.get('/removes',function(req,res){
    let shop_id = req.query.id;
    Shop.findOneAndRemove({_id:shop_id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        data.deleted = true;
        data.save();
        res.json({error:0,message:'删除成功'})
    })

})

//分类数据
router.post('/goods',function(req,res){
    // console.log(req.body.condition)
    Shop.find({checked:req.body.condition}).then(function(datas){
        res.json({error:0,message:datas})
    }).catch(function(err){
        res.end(err);
    })
})
// 所有分类
router.get('/tags',function(req,res){
    Shop.distinct('checked').then(function(datas){
        res.json({error:0,message:datas})
    }).catch(function(err){
        res.end(err)
    })
})

// 修改商品数量
router.post('/cartEdit',function(req,res,next){
    var userId = req.session.user._id,
    productId = req.body.productId,
    productNum = req.body.productNum,
    xuan = req.body.xuan;
    User.update({'_id':userId,'cart.productId':productId},{
        'cart.$.productNum':productNum,
        'cart.$.xuan':xuan,
    },function(err,data){
        if(err){
            res.json({error:1,msg:err})
        }else{
            res.json({error:0,result:'suc'})
        }
    })

})

// 获取修改商品页面的原始商品信息
router.get('/upshop/:id',function(req,res){
    // console.log(req.params.id);
    var id = req.params.id;
    Shop.findOne({_id:id}).exec(function(err,data){
        if(err){
           return res.json({error:1,message:'获取失败'})
        }
        res.json({error:0,message:data});
    })
})
// 修改商品
router.post('/upadd/:id',function(req,res){
    // console.log('req.body')
    // console.log(req.body)
    var name = req.body.name;
    var yuanPrice = req.body.yuanPrice;
    var describe = req.body.describe;
    var id = req.params.id;
    console.log(id)
    Shop.findOne({'_id':id}).exec(function(err,datas){
        if(err){
            return res.json({error:1,message:err})
        }
        datas.name = name;
        datas.yuanPrice = yuanPrice;
        datas.describe = describe;
        datas.save();
        var obj = {};
        obj.data = datas;
        res.json({error:0,message:obj})
        
    })



})

// 修改头像
router.post('/infos',upload.single('photo'),function(req,res,next){
    // console.log('进来了');
    // console.log(req.body)
    var user_id = req.session.user._id;
    // console.log(user_id)
        User.findOne({_id:user_id}).exec(function(err,user){
        if(err){
            return res.json({error:1,message:err})
        }
        // console.log(user);
        user.head = req.file.filename;
        req.session.user = user;
        user.save();
        // console.log(user);/
        res.json({error:0,message:'修改成功'});
    })
})

// 详情至立即购买
// router.get('/promptly',function(req,res){

// })
// 添加评论
router.post('/addping/:id',upload.array('photo'),function(req,res){

    // console.log(1);
    // console.log(2);
    var arr = [];
    for(var i = 0 ; i < req.files.length; i++){
        arr.push(req.files[i].filename)
    }

    // console.log(3);
    // console.log(req.session.user)
    req.body.authorName = req.session.user.name;
    // console.log(3);
    req.body.authorHead = req.session.user.head;
    // console.log(3);
    req.body.time = new Date().toLocaleString();
    // console.log(3);
    req.body.commentImages = arr;
    
      console.log('req.params.id');
    //   console.log(req.params.id);
        var id = req.params.id
    Shop.findOne({'_id':id}).exec(function(err,data){
        if(err){
           return res.json({error:1,message:'获取商品失败'});
        }
        // let newShop = new Shop(req.body);
        console.log(4);
        data.comment.push(req.body);
        data.save();
        // res.json({error:0,message:'评论成功'})
        guanliId = data.guanliId;
        console.log(1111111)
        console.log(guanliId)
        Man.findOne({'_id':guanliId}).exec(function(err,user){
            if(err){
                return res.json({error:1,message:'获取商品失败'});
            }
            var name = data.name;
            req.body.sname = name;
            user.cart.push(req.body)
            user.save();
            res.json({error:0,message:'评论成功'})
        })
    })
})


// 消息页面
router.get('/xiaoxi',function(req,res){
    // console.log(req.session.poat._id);
    var id = req.session.poat._id;
    Man.findOne({'_id':id}).exec(function(err,user){
        if(err){
            return res.json({error:1,message:'获取商品失败'});
        }
        
        res.json({error:0,message:user.cart})
    })

})

// 消息页面删除
router.get('/pingshan',function(req,res){
    var ins = req.body.ins;
    var id = req.session.poat._id;
    Man.findOne({'_id':id}).exec(function(err,user){
        if(err){
            return res.json({error:1,message:'获取商品失败'});
        }
        user.cart.splice(ins,1);
        user.save();
        res.json({error:0,message:'chengg'})
    })
})

//点击结算
router.post('/sure',function(req,res,next){


    // console.log('sure')

    var shops = req.body.arr;
    // console.log(shops);
    // console.log(shops);
    var id = req.session.user._id;
    // console.log(id)
    User.findOne({'_id':id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        // console.log('data.goumai');
        // console.log(data.goumai);
        
        data.goumai.push(shops);
        data.save();
        res.json({error:0,message:'添加至立即购买数组成功'})
    })
});
//提交页面获取从购物车选择的商品
router.get('/huo',function(req,res,next){
    var id = req.session.user._id;
    User.findOne({'_id':id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        // console.log(data.goumai);
        res.json({error:0,message:data.goumai})
    })
});

// 加载更多
router.get('/shopp',function(req,res){
    // console.log(req.query.limit);
    var num = req.query.limit * 1;
    Shop.find().sort({'yuanPrice':1}).limit(2*num).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        console.log(data)
        res.json({error:0,message:data})
    })
})
// 加载更多
// router.get('/shpoo',function(req,res){
//     // console.log(req.query);
//     var num = req.query.limit * 1;
//     // var arrNum = req.query.offset * 1;
//     Shop.find().sort({'yuanPrice':-1}).limit(num).exec(function(err,data){
//         if(err){
//             return res.json({error:1,message:err})
//         }
//         res.json({error:0,message:data})
//     })
// })
// 显示全部地址
router.get('/adddizhi',function(req,res){
     var id = req.session.user._id;
     var shop = req.body.shop;
        User.findOne({'_id':id}).exec(function(err,data){
            if(err){
                return res.json({error:1,message:err})
            }
            res.json({error:0,message:data.dizhi})
        })
})
// 添加地址
router.post('/adddizhi',function(req,res){
     var id = req.session.user._id;
     console.log('req.body.shop')
     console.log(req.body.shop)
     var shop = req.body.shop;
        User.findOne({'_id':id}).exec(function(err,data){
            if(err){
                return res.json({error:1,message:err})
            }
            console.log(data.dizhi)
            data.dizhi.push(shop);
            data.save();
        })
})
// 删除地址
router.post('/remshan',function(req,res){
    console.log('req.body')
    console.log(req.body)
    var ins = req.body.ins;
    var id = req.session.user._id;
    User.findOne({'_id':id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        // console.log(data.dizhi)
        data.dizhi.splice(ins,1);
        data.save();
    })
})
// 选择地址
router.post('/adzhi',function(req,res){
    // console.log('req.body')
    // console.log(req.body)
    var ins = req.body.ins;
    var id = req.session.user._id;
    User.findOne({'_id':id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        console.log('-----------------')
        console.log(data.dizhi[ins])
        for(var i = 0; i < data.dizhi.length; i++){
           if( i != ins){
               console.log(5)
               data.dizhi[i].isDizhi = false;
           }else{
               data.dizhi[i].isDizhi = true;
           }
        }
        console.log(data.dizhi);
        let us = new User(data);
        us.save();
        req.session.user = data;

        res.json({error:0,message:'chengg'})
    })
})
router.get('/huodzhi',function(req,res){
    // console.log('req.body')
    // console.log(req.body)
    var id = req.session.user._id;
    User.findOne({'_id':id}).exec(function(err,data){
        if(err){
            return res.json({error:1,message:err})
        }
        // console.log(data.dizhi)
        for(var i = 0; i < data.dizhi.length; i++){
           if( data.dizhi[i].isDizhi == true){
                res.json({error:0,message:data.dizhi[i]})
           }
        }
        
    })
})

// 点击立即付款
// 1.删除购物车数组cart:[]中与提交数组goumai:[]相同的数据
// 2.将goumai:[]数组中的数据传递到全部订单dingdan:[]
//    数组中的待收货数组shou:[]中
// 3.清空提交数组goumai:[]中的全部数据
router.post('/goumai',function(req,res){
    // console.log(req.session.user._id)
    var user_id = req.session.user._id;
    // console.log(1)
     User.findOne({ '_id': user_id}).exec(function(err,data){
        // console.log(2)
        if(err){
            return res.end(err);
        }
        for(var i = 0; i < data.cart.length; i++){
            for(var j = 0; j < data.goumai.length; j++){
                for(var h = 0; h < data.goumai[j].length; h++){
                    
                    // console.log('31433455634545333')

                    // console.log(data.dingdan.receving);
                    data.dingdan.receving.push(data.goumai[j][h]);
                    // console.log(data.cart[i].productName);
                    // console.log(data.goumai[j][h].productName);
                    if(data.cart[i].productName == data.goumai[j][h].productName){
                        // console.log(7)
                        data.cart.splice(i,1);
                    }

                }
            }
            // console.log(8)

            data.goumai.splice(0,data.goumai.length);
        }
        // console.log(9)
        data.save();
        res.json({error:0,message:'删除成功'})
    })
})

// // 点击返回时在订单数组中删除当前商品
router.post('/fanhui',function(req,res){
    // console.log('=============');
    // console.log(req.body.arr);
    var user_id = req.session.user._id;
    // console.log(1)
     User.findOne({ '_id': user_id}).exec(function(err,data){
        // console.log(2)
        if(err){
            return res.end(err);
        }
        data.goumai.splice(0,data.goumai.length);
        data.save();
        res.json({error:0,message:'删除成功'})
    })
})

// 待收货
router.get('/receving',function(req,res){
    var user_id = req.session.user._id;
     User.findOne({ '_id': user_id}).exec(function(err,data){
        if(err){
            return res.end(err);
        }
        // console.log(data)
        res.json({error:0,message:data.dingdan.receving})
    })
})
// 点击确认收货
router.post('/receving',function(req,res){
    // console.log(req.body);
    var ins = req.body.ins;
     var user_id = req.session.user._id;
     User.findOne({ '_id': user_id}).exec(function(err,data){
        if(err){
            return res.end(err);
        }
        // console.log(1111111);
        // console.log(data.dingdan.achieve)
        // console.log(2222222);
        // console.log(data.dingdan.receving[ins])

        data.dingdan.achieve.push(data.dingdan.receving[ins])
        data.dingdan.receving.splice(ins,1);
        // console.log(333333);
        //  console.log(data.dingdan.receving)
         data.save();
        res.json({error:0,message:data.dingdan.receving})
    })
})

// 我的订单
router.get('/dingd',function(req,res){
    var user_id = req.session.user._id;
     User.findOne({ '_id': user_id}).exec(function(err,data){
        if(err){
            return res.end(err);
        }
        // console.log(data)
        
        res.json({error:0,message:data.dingdan})
    })
})

// 搜索
router.post('/sousou',function(req,res){
    // console.log('req.body');
    // console.log(req.body);
    var sou = validator.trim(req.body.sou);
    // console.log(sou)
    var str = RegExp(sou,'i');
    Shop.find({name:str}).exec(function(err,data){
        if(err){
           return res.json({error:1,message:'没有找到相关内容'})
        }
        res.json({error:0,message:data})
    })

})



module.exports = router;
